package com.lzx.adx.report.support.strategy.v2.media;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.OPPO)
public class OppoCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);


        long currentTimeMillis = System.currentTimeMillis();
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(accountDTO.getSspApiUrl());

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("imei", "");
        reqMap.put("ouId", encode(reportDTO.getOaid().getBytes(StandardCharsets.UTF_8)
                , jsonObject.getString("base64Key")));
        reqMap.put("timestamp", currentTimeMillis);
        reqMap.put("pkg", jsonObject.getString("pkg"));
        reqMap.put("dataType", eventType);
        reqMap.put("channel", 1);
        reqMap.put("type", 2);
        reqMap.put("ascribeType", 1);
        reqMap.put("adId", reportDTO.getTagId());
        String resultPams = JSON.toJSONString(reqMap);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("signature", SecureUtil.md5(resultPams + currentTimeMillis + jsonObject.getString("salt")).toLowerCase());
        headerMap.put("timestamp", String.valueOf(currentTimeMillis));
        log.info("OPPO的请求参数为{},OPPO的请求头为{}",resultPams,JSONObject.toJSONString(headerMap));
        log.info("账号id{},请求id{} 给快手上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), accountDTO.getSspApiUrl());
        String result = HttpUtil.createPost(accountDTO.getSspApiUrl())
                .headerMap(headerMap, false)
                .body(resultPams)
                .timeout(5000)
                .execute()
                .body();
        log.info("账号id{},请求id{} 给OPPO上报回传结果为 {}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);
        return ResponseEntity.ok(new Result());
    }


    public String encode(byte[] data, String base64Key) {
         try {
             final Key dataKey = new SecretKeySpec(Base64.decodeBase64(base64Key),
                     "AES");
             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
             cipher.init(Cipher.ENCRYPT_MODE, dataKey);
             byte[] encryptData = cipher.doFinal(data);
             return Base64.encodeBase64String(encryptData).replaceAll("\r",
                     "").replaceAll("\n", "");
         }catch (Exception e){
             log.error("加密参数出现了异常，异常的错误为{}",e);
         }
         return null;
    }
}
